<template>
  <el-form :model="ruleForm" :rules="rules" ref="validateForm" class="login-ruleForm">
    <el-form-item prop="username">
      <el-input placeholder="用户账号" v-model="ruleForm.username">
        <template #prefix>
          <icon-user theme="outline" size="16" fill="#999" />
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input @keyup.enter="handleLogin" placeholder="登录密码" type="password" v-model="ruleForm.password">
        <template #prefix>
          <icon-lock theme="outline" size="16" fill="#999" />
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <div class="login-check">
        <el-checkbox v-model="checkedPwd">记住密码</el-checkbox>
        <el-button text type="primary">忘记密码</el-button>
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :loading="loading" class="login-btn" round @click="handleLogin">
        登录账号
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { reactive, toRefs, ref, unref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user'; // 引入 Pinia Store

export default {
  setup() {
    const router = useRouter();
    const userStore = useUserStore(); // 使用 Pinia Store
    const validateForm = ref(null);

    const state = reactive({
      ruleForm: {
        username: 'admin',
        password: 'admin',
      },
      loading: false,
      checkedPwd: false,
      redirect: undefined,
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }], // 默认中文提示
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }], // 默认中文提示
      },
    });

    // 监听路由变化
    watch(
      () => router.currentRoute.value, // 修改为直接访问 currentRoute.value
      (route) => {
        state.redirect = (route.query && route.query.redirect) || '/';
      },
      { immediate: true }
    );

    // 登录处理逻辑
    const handleLogin = async () => {
      const form = unref(validateForm);
      if (!form) return;

      await form.validate((valid) => {
        console.log('valid',valid)
        if (valid) {
          state.loading = true;
          userStore
            .login(state.ruleForm) // 调用 Pinia Store 中的 login 方法
            .then((body) => {
              console.log(body)
              const routerPath =
                state.redirect === '/404' || state.redirect === '/401' ? '/' : state.redirect;

              router.push(routerPath).catch((error) => {
                console.error('路由跳转失败:', error);
                // 可以在这里添加更多的错误处理逻辑，比如显示错误提示框
              });

              // const routerPath =
              //   state.redirect === '/404' || state.redirect === '/401' ? '/' : state.redirect;
              // router.push(routerPath).catch(() => {});
              state.loading = false;
            })
            .catch(() => {
              console.log('login failing')
              state.loading = false;
            });
        }
      });
    };

    return {
      ...toRefs(state),
      validateForm,
      handleLogin,
    };
  },
};
</script>
<style lang="scss" scoped>
.login-ruleForm {
  margin-top: 1rem;

  :deep(.el-input__prefix) {
    top: 2px;
    padding: 0 4px;
  }

  .login-methods {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }

  .login-btn {
    width: 100%;
  }

  .login-check {
    width: 100%;
    display: flex;
    align-content: center;
    justify-content: space-between;
  }
}
</style>
